import $ from "jquery";
import { http, toast, ss, loading, format, numbers, editor } from "@/utils";
import iconBtnSubmit from "../assets/images/icon-btn-submit.svg";
import iconBtnCancel from "../assets/images/icon-btn-cancel.svg";
import { helperToolbar } from "../views/home/helperToolbar.js";

//文件尺寸，单位为M
var fileSizeM;
var editorConfig;
var fileFinalName;
var parentDocumentTitle;
var provideHome;

const setSealCurrentOperateNoneWhenApiResponse = () => {
  if ($("#btnSealAddContinued").hasClass("active")) {
    //当前操作位连续签章
  } else {
    provideHome.methods.setSealCurrentOperateName("");
  }
};

export const seal = {
  /**
   * 转换印章id，
   * @param {*} signatureDomainId
   * @returns
   *    批量印章，返回 印章 id_x
   *    普通印章，返回 印章 id
   */
  formatSignatureDomainId(signatureDomainId) {
    return signatureDomainId.replace(/_.+/, "_x");
  },
  setProvideHome(payload) {
    provideHome = payload;
  },
  /**
   * 创建印章确认容器，返回容器元素
   * @param {*} param0
   *    imgWidth: 印章图片显示的宽度
   *       骑缝章，不传入此参数。因骑缝章使用的是 div.gap-drag-area 的 --sealWidth
   *    imgHieght: 印章图片显示的高度
   *       骑缝章，不传入此参数。因骑缝章使用的是 div.gap-drag-area 的 --sealHeight
   *    imgSrc: 印章图片地址,
   *    sealType: gap骑缝章、notGap非骑缝章
   * @returns
   */
  createConfirmSeal({
    imgWidth,
    imgHeight,
    imgSrc,
    sealType = "notGap",
    rotation = 0,
  } = {}) {
    let boxConfirmSeal = document.createElement("div");
    boxConfirmSeal.dataset.sealType = sealType;
    boxConfirmSeal.dataset.showerRotation = rotation;
    boxConfirmSeal.className = "box-confirm-seal box-unfinish box-rotation";
    if (imgWidth) {
      boxConfirmSeal.style.setProperty("--sealWidth", imgWidth + "px");
      boxConfirmSeal.style.setProperty("--sealHeight", imgHeight + "px");
    }

    //页面当前缩放比例
    boxConfirmSeal.innerHTML = `
      <img src="${imgSrc}" class="w-full h-full shower"/>
      <div class="box-confirm-btn flex">
        <div class="btn-item btn-cancel cursor-pointer" title="取消"
        >
          <img class="block w-full h-full " src="${iconBtnCancel}" />
        </div>
        <div class="btn-item btn-submit cursor-pointer" title="确定"
        >
          <img class="block w-full h-full " src="${iconBtnSubmit}" />
        </div> 
      </div>

    `;

    $(boxConfirmSeal)
      .on("mouseover", function () {
        $(".box-confirm-btn", this).removeClass("hidden").addClass("flex");
      })
      .on("mouseout", function () {
        $(".box-confirm-btn", this).removeClass("flex").addClass("hidden");
      });
    return boxConfirmSeal;
  },
  /**
   * 获得当前缩放因子
   * @returns
   */
  getScaleFactor() {
    // var scale = PDFViewerApplication.toolbar.pageScale;
    var scale = $("#viewer").css("--scale-factor");
    return scale;
  },
  /**
   * 获取印章实际坐标
   */
  getRealPosition(el) {
    let scaleFactor = this.getScaleFactor();
    let { left, top, showerRotation = 0, pageWidth, pageHeight } = el.dataset;
    let ret;
    if (showerRotation == 0) {
      ret = {
        left: +numbers.division(left, scaleFactor).toFixed(2),
        top: +numbers.division(top, scaleFactor).toFixed(2),
      };
    } else if (showerRotation == 90) {
      //旋转90度，X轴当Y轴使，Y轴当X轴使，且X轴取反
      ret = {
        left: +numbers.division(top, scaleFactor).toFixed(2),
        top: +numbers
          .division(pageWidth - left - $(el).width(), scaleFactor)
          .toFixed(2),
      };
    } else if (showerRotation == 180) {
      ret = {
        left: +numbers
          .division(pageWidth - left - $(el).width(), scaleFactor)
          .toFixed(2),
        top: +numbers
          .division(pageHeight - top - $(el).height(), scaleFactor)
          .toFixed(2),
      };
    } else if (showerRotation == 270) {
      ret = {
        left: +numbers
          .division(pageHeight - top - $(el).height(), scaleFactor)
          .toFixed(2),

        top: +numbers.division(left, scaleFactor).toFixed(2),
      };
    }
    // console.log("getRealPosition ========= ", ret);
    return ret;
  },
  move(el, targetPosition) {
    let $page = $(el).closest(".page");
    let { left, top, containerScrollTop } = targetPosition;
    el.style.transform = `translate(${left}px , ${top}px)`;
    el.dataset.left = left;
    el.dataset.top = top;
    el.dataset.pageWidth = $page.width();
    el.dataset.pageHeight = $page.height();
    el.dataset.containerScrollTop = containerScrollTop;
  },
  initEditor(options = {}) {
    editorConfig = options;
    const { document, toolsExcludes, callBackUrl } = editorConfig;
    const sealDocument =
      Array.isArray(document) && document.length > 0 ? document[0] : document;
    if (sealDocument && sealDocument.token) {
      provideHome.methods.resetAll();
      provideHome.isLoadingSignHistory = false;
      this.initFile(sealDocument, callBackUrl);
      /** 初始化界面 */
      editor.initUI(toolsExcludes);
    }
  },
  /** 初始化文件 */
  async initFile(documentConfig, callBackUrl) {
    $("#appLoading").show();
    PDFViewerApplication.close();
    refDialogBlock.value?.close();
    const [err, res] = await http.post({
      showError: false,
      data: {
        serviceCode: "electronicSealSignatureInitialize",
        featureCode: "initializeFile",
        businessData: {
          document: [documentConfig],
          callBackUrl,
        },
      },
    });
    if (res) {
      this.pollingFileStatus(res.transactionId);
    } else {
      loading.close();
      refDialogBlock.value?.show(err.message);
    }
  },
  /** 轮询 '初始化文件' 状态 */
  async pollingFileStatus(transactionId) {
    let timer;

    const _pollingStop = () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
    const _pollingStart = async () => {
      const [err, res] = await http.post({
        showError: false,
        data: {
          serviceCode: "electronicSealSignatureInitialize",
          featureCode: "getInitializeFileResult",
          businessData: {
            transactionId,
          },
        },
      });
      if (res) {
        let { initializeStatus, initializeDesc, fileSize } = res;
        if (initializeStatus == 10) {
          // 10 初始化中
          timer = setTimeout(_pollingStart, 2000);
        } else if (initializeStatus == 20) {
          // 20 已完成初始化
          _pollingStop();
          ss.set("fileId", res.fileId);
          // 文件单位由字节转为兆
          fileSizeM = (fileSize / 1024 ** 2).toFixed(2);
          this.previewFile(res.fileId);
        } else if (initializeStatus == 30) {
          // 30 初始化失败
          toast.error(initializeDesc);
          _pollingStop();
          loading.close();
        }
      } else {
        _pollingStop();
        loading.close();
        refDialogBlock.value?.show(err.message);
      }
    };
    _pollingStart();
  },
  /** 预览文件 */
  async previewFile(fileId, prevAction = "") {
    let fileSize1 = 100,
      fileSize2 = 500;

    // if (fileSizeM >= fileSize1) {
    if (prevAction == "addSeal") {
      loading.setText(`印章已加盖，正在加载文档…`);
    }
    // else {
    //   loading.setText(`正在加载文档，文档较大，努力加载中…`);
    // }
    // }
    const [err, res] = await http.post({
      success: true,
      showError: false,
      responseType: "blob", // 设置响应类型为 blob
      timeout: Number.MAX_SAFE_INTEGER,
      data: {
        serviceCode: "electronicSealSignatureInitialize",
        featureCode: "filePreview",
        businessData: {
          fileId,
        },
      },
    });
    provideHome.methods.resetPartial();
    setSealCurrentOperateNoneWhenApiResponse("");
    loading.close();
    if (res) {
      //优先使用 editorConfig.fileName
      fileFinalName =
        editorConfig.document?.fileName ||
        format.getFileNameFromResponseHeaders(res.headers);
      await PDFViewerApplication.open({
        url: URL.createObjectURL(res.data),
        originalUrl: fileFinalName,
      });
      /** 初始化侧边栏 */
      $("#appLoading").hide();
      this.afterPageRender();
    } else {
      refDialogBlock.value?.show(err.message);
      $("#appLoading").hide();
    }
  },
  afterPageRender() {
    provideHome.isLoadingSignHistory = false;
    setTimeout(() => {
      //延迟操作，防止页面未渲染完成，引发一些莫名奇妙的问题
      if (
        $("#btnSealAddContinued").hasClass("active") &&
        window.$hoverSealBox
      ) {
        window.$hoverSealBox.appendTo("#viewer");
      }
      if ($("#viewAttachments").hasClass("active")) {
        console.log('provideHome: ', provideHome);
        //tab “签章历史”处于激活状态
        PDFViewerApplication.pdfSidebar.isOpen = true;
        provideHome.isLoadingSignHistory = true;
        // provideHome.getSignatureList(true);
      }
    }, 1000);
  },
  setParentDocumentTitle() {
    if (!parentDocumentTitle) {
      parentDocumentTitle = window.parent?.document.title;
    }
    if (window.parent) {
      window.parent.document.title = fileFinalName;
    }
  },
  resetParentDocumentTitle() {
    if (parentDocumentTitle) {
      window.parent.document.title = parentDocumentTitle;
    }
  },
  setParentDocumentTitle() {
    if (!parentDocumentTitle) {
      parentDocumentTitle = window.parent?.document.title;
    }
    if (window.parent) {
      window.parent.document.title = fileFinalName;
    }
  },
  resetParentDocumentTitle() {
    if (parentDocumentTitle) {
      window.parent.document.title = parentDocumentTitle;
    }
  },
  //
  /**
   * 印章添加
   * @param {*} params
   * params = {
   *    fileId 当前文件ID
   *    signatureInfo:{
   *        signatureType   custom表示普通签章， pageSeal表示骑缝章
   *        page  所有页用0表示，多页码用,隔开(英文逗号)
   *        x  坐标定位X轴，当骑缝章时:x=0
   *        y  坐标定位Y轴
   *        keyword  定位关键词
   *    }
   *    sealSn  印章id
   *    positionType   定位模式：1坐标定位；2:关键词定位
   *    signContinued  是否连续签章 00:单次签章 、01：连续签章
   *    sealType  印章类型 00手写签名/01公章/02合同章/03财务章/04人名章/05法定代表人章
   * }
   */
  async doSealAdd(params) {
    // loading.show({ text: "印章正在加盖…" });
    loading.showType2();
    let [err, res] = await http.post({
      data: {
        serviceCode: "electronicSealSignature",
        featureCode: "fileElectronicSealSignature",
        businessData: params,
      },
    });
    if (res) {
      sessionStorage.setItem('transactionId', res.transactionId)
      this.pollingSealAddStatus(res.transactionId);
    } else {
      provideHome.methods.setBoxTemporarySeal(null);
      setSealCurrentOperateNoneWhenApiResponse();
      loading.close();
    }
  },
  /** 轮询 '印章添加' 结果 */
  async pollingSealAddStatus(transactionId) {
    let timer;
    const _pollingStop = () => {
      if (timer) {
        clearInterval(timer);
      }
    };
    const _pollingStart = async () => {
      const [err, res] = await http.post({
        data: {
          serviceCode: "electronicSealSignature",
          featureCode: "getFileElectronicSealSignatureResult",
          businessData: {
            transactionId,
          },
        },
      });
      if (res) {
        let { signStatus, signStatusDesc } = res;
        if (signStatus == 10) {
          //10:加章中
          timer = setTimeout(_pollingStart, 2000);
        } else if (signStatus == 20) {
          //20：加章完成
          _pollingStop();
          ss.set("fileId", res.fileId);
          console.log("newFileId", res.fileId);
          this.previewFile(res.fileId, "addSeal");
          setSealCurrentOperateNoneWhenApiResponse();
        } else if (signStatus == 30) {
          //30：加章失败
          toast.error(signStatusDesc);
          _pollingStop();
          provideHome.methods.setBoxTemporarySeal(null);
          setSealCurrentOperateNoneWhenApiResponse();
          loading.close();
        }
      } else {
        _pollingStop();
        provideHome.methods.setBoxTemporarySeal(null);
        setSealCurrentOperateNoneWhenApiResponse();
        loading.close();
      }
    };
    _pollingStart();
  },
  /** 退出加章流程 */
  async exitAppLinkWhenSealAdd() {
    if (/btnSealAdd/.test(provideHome.sealCurrentOperateName)) {
      // console.log("退出加章流程 ========");
      //处在加章流程中
      await http.post({
        showError: false,
        data: {
          serviceCode: "electronicSealSignature",
          featureCode: "exitElectronicSealSignature",
        },
      });
    }
  },
};
